package com.kyxx.topics.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.MyCommonTitle;
import com.loopj.android.http.RequestParams;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2016/7/22.
 */
public class UserModifyPwdActivity extends Activity implements View.OnClickListener{
    private MyCommonTitle myCommonTitle;
    private EditText ed_code, ed_pwd;
    private TextView tvDescription, btn_send_code, btn_submit;
    private String mobile, code, password;
    private static String APPKEY = "1770c6f012dda";
    private static String APPSECRET = "8196301ef118a8d76c717c190c51ecfa";
    private JSONObject jsonObject, jsonObject1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mobile = getIntent().getStringExtra("mobile");
        setContentView(R.layout.activity_user_modify_pwd);

        // 初始化短信验证
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);

        /* 发送手机验证码 */
        new MyCount(60000, 1000).start();// 一分钟倒计时
        SMSSDK.getVerificationCode("86", mobile);
        initView();
    }

    private void initView() {
        myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_myTitle);
        myCommonTitle.setTitle("修改密码");

        tvDescription = (TextView) findViewById(R.id.tv_description);
        tvDescription.setText("已向您的手机为 " + Html.fromHtml("<font color =#FF0000> " + mobile + "</font>" + " 发送了验证码"));
        ed_code = (EditText) findViewById(R.id.ed_code);
        btn_send_code = (TextView) findViewById(R.id.btn_send_code);
        ed_pwd = (EditText) findViewById(R.id.ed_password);
        btn_submit = (TextView) findViewById(R.id.btn_submit);
        ed_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ed_code.setBackgroundResource(R.drawable.bg_circle_white);
            }
        });
        ed_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ed_pwd.setBackgroundResource(R.drawable.bg_circle_white);
                btn_submit.setBackgroundResource(R.drawable.bg_circle_bule);
                btn_submit.setOnClickListener(UserModifyPwdActivity.this);
            }
        });
    }

    public void onClick(View view) {
        code = ed_code.getText().toString().trim();
        password = ed_pwd.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_send_code:
                btn_send_code.setOnClickListener(null);
                new MyCount(60000, 1000).start();// 一分钟倒计时
                SMSSDK.getVerificationCode("86", mobile);
                break;
            case R.id.btn_submit:
                if (!TextUtil.isCode(code, 4)) {
                    Tools.toast(UserModifyPwdActivity.this, "您输入的验证码不正确！");
                    return;
                }
                if (!TextUtil.isPasswordLengthLegal(password)) {
                    Tools.toast(UserModifyPwdActivity.this, "密码有效长度为6-20位！");
                    return;
                }
                SMSSDK.submitVerificationCode("86", mobile, code);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("result", "result=" + result);
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                    Tools.toast(UserModifyPwdActivity.this, "提交验证码成功");
                    submitData();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Tools.toast(UserModifyPwdActivity.this, "验证码已经发送");
                }
            } else {
                ((Throwable) data).printStackTrace();
//                 int resId = getStringRes(UserRegisterCodeActivity.this,"smssdk_network_error");
                Tools.toast(UserModifyPwdActivity.this,
                        event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证码频繁，请稍后再试！" : "验证码错误");
                // if (resId > 0) {
                // Tools.toast(UserRegisterActivity.this, resId + "");
                // }
            }
        }

        /**
         * 调用修改密码接口
         */
        private void submitData() {
//        jsonObject = new JSONObject();
//        jsonObject.put("UserId", BaseApp.getModel().getId());
//        jsonObject.put("Password", password);
//        StringEntity s = null;
//        try {
//            s = new StringEntity(jsonObject.toString(), "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
            RequestParams params = new RequestParams();
            params.put("UserId", BaseApp.getModel().getId());
            params.put("Password", password);
            RestClient.post(UrlUtils.MODIFYPSW, params, UserModifyPwdActivity.this, new ResponseListener(UserModifyPwdActivity.this,true) {

                @Override
                public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

                }

                @Override
                public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                    super.failed(arg0, arg1, result);
                }
            });
        }
    };

    /* 定义一个倒计时的内部类 */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btn_send_code.setText(Html.fromHtml("<font <color=#FFFFFF>" + "重新发送" + "</font>"));
            btn_send_code.setBackgroundResource(R.drawable.bg_circle_bule);
            btn_send_code.getResources().getColor(R.color.white);
            btn_send_code.setOnClickListener(UserModifyPwdActivity.this);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_send_code.setText("重新发送(" + millisUntilFinished / 1000 + "S)");
        }
    }
}

